using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.Common.Results;
using ERP.ERPSystem.WarehouseManagement;
using ERP.ERPSystem.WarehouseManagement.Dto;
using ERP.Team.WarehouseManagement;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace ERP.Application.ERPSystem.WarehouseManagement
{
    /// <summary>
    /// 节假日设置服务实现
    /// </summary>
    public class HolidaysSetServices : ApplicationService, IHolidaysSetServices
    {
        private readonly IRepository<HolidaysSet, int> _holidaysSetRepository;

        public HolidaysSetServices(IRepository<HolidaysSet, int> holidaysSetRepository)
        {
            _holidaysSetRepository = holidaysSetRepository;
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<HolidaysSetPagedResult>> GetPagedListAsync(HolidaysSetQueryDto query)
        {
            try
            {
                // 构建查询条件
                var queryable = await _holidaysSetRepository.GetQueryableAsync();
                
                // 应用筛选条件
                if (query.Year.HasValue)
                {
                    queryable = queryable.Where(x => x.HolidaysTime.Year == query.Year.Value);
                }
                
                if (query.Month.HasValue)
                {
                    queryable = queryable.Where(x => x.HolidaysTime.Month == query.Month.Value);
                }
                
                if (!string.IsNullOrEmpty(query.HolidaysType))
                {
                    queryable = queryable.Where(x => x.HolidaysType == query.HolidaysType);
                }
                
                if (query.StartDate.HasValue)
                {
                    queryable = queryable.Where(x => x.HolidaysTime >= query.StartDate.Value);
                }
                
                if (query.EndDate.HasValue)
                {
                    queryable = queryable.Where(x => x.HolidaysTime <= query.EndDate.Value);
                }
                
                var totalCount = queryable.Count();
                var entities = queryable
                    .Skip((query.PageNumber - 1) * query.PageSize)
                    .Take(query.PageSize)
                    .OrderBy(x => x.HolidaysTime)
                    .ToList();
                
                // 转换为DTO
                var pageData = entities.Select(x => new HolidaysSetDto
                {
                    Id = x.Id,
                    HolidaysTime = x.HolidaysTime,
                    HolidaysType = x.HolidaysType,
                    CreateTime = x.CreateTime,
                    UpdateTime = x.UpdateTime
                }).ToList();
                
                var result = new HolidaysSetPagedResult
                {
                    Items = pageData,
                    TotalCount = totalCount,
                    PageNumber = query.PageNumber,
                    PageSize = query.PageSize
                };
                
                return APIResult<HolidaysSetPagedResult>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<HolidaysSetPagedResult>.CreateError("查询节假日设置列表失败");
            }
        }

        /// <summary>
        /// 根据ID获取详情
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<HolidaysSetDto>> GetByIdAsync(int id)
        {
            try
            {
                var entity = await _holidaysSetRepository.FirstOrDefaultAsync(x => x.Id == id);
                
                if (entity == null)
                {
                    return APIResult<HolidaysSetDto>.CreateError("节假日设置不存在");
                }
                
                var result = new HolidaysSetDto
                {
                    Id = entity.Id,
                    HolidaysTime = entity.HolidaysTime,
                    HolidaysType = entity.HolidaysType,
                    CreateTime = entity.CreateTime,
                    UpdateTime = entity.UpdateTime
                };
                
                return APIResult<HolidaysSetDto>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<HolidaysSetDto>.CreateError("获取节假日设置详情失败");
            }
        }

        /// <summary>
        /// 创建节假日设置
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<HolidaysSetDto>> CreateAsync(HolidaysSetCreateDto createDto)
        {
            try
            {
                // 解析日期
                var holidaysTime = createDto.GetHolidaysTime();
                
                // 添加调试日志
                Logger.LogInformation($"开始创建节假日设置 - 原始字符串: {createDto.HolidaysTime}, 解析后: {holidaysTime:yyyy-MM-dd HH:mm:ss} (Kind: {holidaysTime.Kind}), HolidaysType: {createDto.HolidaysType}");
                
                // 检查数据库中是否已存在相同日期的设置
                var existingInDb = await _holidaysSetRepository.FirstOrDefaultAsync(x => x.HolidaysTime.Date == holidaysTime.Date);
                
                if (existingInDb != null)
                {
                    // 如果已存在，则更新
                    existingInDb.HolidaysType = createDto.HolidaysType;
                    existingInDb.UpdateTime = DateTime.Now;
                    
                    var updatedEntity = await _holidaysSetRepository.UpdateAsync(existingInDb, autoSave: true);
                    
                    // 转换为DTO
                    var updatedResult = new HolidaysSetDto
                    {
                        Id = updatedEntity.Id,
                        HolidaysTime = updatedEntity.HolidaysTime,
                        HolidaysType = updatedEntity.HolidaysType,
                        CreateTime = updatedEntity.CreateTime,
                        UpdateTime = updatedEntity.UpdateTime
                    };
                    

                    
                    return APIResult<HolidaysSetDto>.CreateSuccess(updatedResult);
                }
                
                // 创建新实体并保存到数据库
                var entity = new HolidaysSet(holidaysTime, createDto.HolidaysType);
                var savedEntity = await _holidaysSetRepository.InsertAsync(entity, autoSave: true);
                
                // 添加保存后的调试日志
                Logger.LogInformation($"保存到数据库后 - ID: {savedEntity.Id}, HolidaysTime: {savedEntity.HolidaysTime:yyyy-MM-dd HH:mm:ss} (Kind: {savedEntity.HolidaysTime.Kind})");
                
                // 转换为DTO
                var result = new HolidaysSetDto
                {
                    Id = savedEntity.Id,
                    HolidaysTime = savedEntity.HolidaysTime,
                    HolidaysType = savedEntity.HolidaysType,
                    CreateTime = savedEntity.CreateTime,
                    UpdateTime = savedEntity.UpdateTime
                };
                
                // 添加DTO转换后的调试日志
                Logger.LogInformation($"DTO转换后 - HolidaysTimeString: {result.HolidaysTimeString}, HolidaysTimeIso: {result.HolidaysTimeIso}");
                

                
                return APIResult<HolidaysSetDto>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<HolidaysSetDto>.CreateError("创建节假日设置失败");
            }
        }

        /// <summary>
        /// 更新节假日设置
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<HolidaysSetDto>> UpdateAsync(HolidaysSetUpdateDto updateDto)
        {
            try
            {
                // 解析日期
                var holidaysTime = updateDto.GetHolidaysTime();
                
                // 从数据库获取实体
                var entity = await _holidaysSetRepository.GetAsync(updateDto.Id);
                if (entity == null)
                {
                    return APIResult<HolidaysSetDto>.CreateError("节假日设置不存在");
                }
                
                // 更新实体数据
                entity.HolidaysTime = holidaysTime;
                entity.HolidaysType = updateDto.HolidaysType;
                entity.UpdateTime = DateTime.Now;
                
                // 保存到数据库
                var updatedEntity = await _holidaysSetRepository.UpdateAsync(entity, autoSave: true);
                
                // 转换为DTO
                var result = new HolidaysSetDto
                {
                    Id = updatedEntity.Id,
                    HolidaysTime = updatedEntity.HolidaysTime,
                    HolidaysType = updatedEntity.HolidaysType,
                    CreateTime = updatedEntity.CreateTime,
                    UpdateTime = updatedEntity.UpdateTime
                };
                

                
                return APIResult<HolidaysSetDto>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<HolidaysSetDto>.CreateError("更新节假日设置失败");
            }
        }

        /// <summary>
        /// 删除节假日设置
        /// </summary>
        [UnitOfWork]
        public async Task<OperationResult> DeleteAsync(int id)
        {
            try
            {
                // 从数据库删除
                await _holidaysSetRepository.DeleteAsync(id);
                

                
                return OperationResult.SuccessResult("删除成功");
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return OperationResult.ErrorResult("删除节假日设置失败");
            }
        }

        /// <summary>
        /// 批量删除节假日设置
        /// </summary>
        [UnitOfWork]
        public async Task<OperationResult> BatchDeleteAsync(List<int> ids)
        {
            try
            {
                // 批量删除数据库记录
                foreach (var id in ids)
                {
                    await _holidaysSetRepository.DeleteAsync(id);
                }
                
                return OperationResult.SuccessResult($"批量删除成功，共删除{ids.Count}条记录");
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return OperationResult.ErrorResult("批量删除节假日设置失败");
            }
        }

        /// <summary>
        /// 获取指定年月的节假日设置
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<List<HolidaysSetDto>>> GetByYearMonthAsync(int year, int month)
        {
            try
            {
                // 从数据库查询数据
                var entities = await _holidaysSetRepository.GetListAsync(x => 
                    x.HolidaysTime.Year == year && x.HolidaysTime.Month == month);
                
                // 转换为DTO
                var result = entities.Select(x => new HolidaysSetDto
                {
                    Id = x.Id,
                    HolidaysTime = x.HolidaysTime,
                    HolidaysType = x.HolidaysType,
                    CreateTime = x.CreateTime,
                    UpdateTime = x.UpdateTime
                }).OrderBy(x => x.HolidaysTime).ToList();
                
                return APIResult<List<HolidaysSetDto>>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<List<HolidaysSetDto>>.CreateError("获取节假日设置失败");
            }
        }


    }
} 